const { model, order } = require("../models/staff");
const { successHandler, errorHandler } = require("../utils/index")

const addItem = async (obj) => {
    try {
        const res = await model.create(obj);
        return successHandler(res);
    } catch(err) {
        const msg = "新增记录失败";
        return errorHandler(msg);
    }
}

const delItem = async (where = {}) => {
    try {
        const res = await model.destroy({
            where
        });
        if (res > 0) {
            return successHandler(res);
        } else {
            return errorHandler("数据异常，请联系管理员")
        }
    } catch(err) {
        const msg = "删除记录失败";
        return errorHandler(msg);
    }
}

const updateItem = async (where, params) => {
    try {
        const res = await model.update(params, {
            where
        });
        return successHandler(res)
    } catch(err) {
        const msg = "更新失败";
        console.log('errrr:', err)
        return errorHandler(msg);
    }
}

const getList = async (obj) => {
    // await model.sync({ force: true });
    // console.log("用户模型表刚刚(重新)创建！");
    const { where = '', paging = false, page = 1, pageSize = 20, attributes = '', sort = ''} = obj;
    try {
        const options = {};
        if (paging) {
            options.offset = (page - 1) * pageSize;
            options.limit = pageSize;
        }
        if (where) {
            options.where = where;
        }
        if (attributes) {
            options.attributes = attributes;
        }
        if (sort) {
            options.order = sort;
        } else {
            options.order = order;
        }
        const res = await model.findAll(options);
        return successHandler(res);
    } catch (err) {
        const msg = '查询记录失败';
        return errorHandler(msg);
    }
}

const getItem = async (where) => {
    try {
        const res = await model.findOne();
    } catch(err) {
        const msg = "查询记录失败";
        return errorHandler(msg);
    }
}

const getCount = async (where = {}) => {
    try {
        const res = await model.count({ where });
        return successHandler(res);

    } catch(err) {
        const msg = "查询记录数量失败";
        return errorHandler(msg);
    }
}

module.exports = {
    addItem,
    delItem,
    updateItem,
    getList,
    getItem,
    getCount
}